<template>
  <view>
    <view class="bg-gradient-to-br from-primary/20 via-secondary/10 to-light min-h-screen my-posts-container" :class="{ 'mobile': isMobile, 'dark': isDarkMode }">
      <!-- Header -->
      <view class="page-header">
        <h1 class="header-title">
          <i class="fa fa-book-open"></i> 我的帖子
        </h1>
      </view>

      <!-- 顶部导航 -->
      <view class="bg-white shadow-md">
        <view class="max-w-5xl mx-auto px-4 py-3 flex items-center justify-between">
          <view class="flex items-center gap-4">
            <button class="text-primary hover:text-primary/80" @tap="navigateBack">
              <text class="fa fa-arrow-left"></text> 返回个人中心
            </button>
            <text class="text-xl font-bold text-dark">我的动态</text>
          </view>
          <view class="flex items-center gap-3">
            <button class="btn-outline" @tap="navigateToSquare">
              <text class="fa fa-th-large mr-1"></text>动态广场
            </button>
            <button class="btn-primary" @tap="showPostModal">
              <text class="fa fa-plus mr-1"></text>发布动态
            </button>
          </view>
        </view>
      </view>

      <!-- 主要内容区 -->
      <view class="max-w-3xl mx-auto py-8 px-4">
        <!-- 动态列表 -->
        <view v-if="posts.length > 0" class="space-y-6">
          <view v-for="post in posts" :key="post.id" class="post-card">
            <view class="flex items-start gap-4">
              <view class="flex-shrink-0">
                <image
                  :src="getAvatarUrl(post.userAvatar)"
                  class="rounded-full" 
                  style="width: 48px; height: 48px;"
                ></image>
              </view>
              <view class="flex-grow">
                <view class="flex items-center justify-between">
                  <text class="font-semibold text-dark">{{ post.userName }}</text>
                  <text class="text-sm text-gray-500">{{ formatTime(post.createdAt) }}</text>
                </view>
                <text class="mt-2 text-gray-700">{{ post.content }}</text>
                <view class="mt-4 flex items-center justify-between">
                  <view class="flex items-center gap-4">
                    <view class="flex items-center gap-1 text-gray-500">
                      <text class="fa fa-heart-o"></text>
                      <text>{{ post.likes }}</text>
                    </view>
                  </view>
                  <button 
                    class="text-red-500 hover:text-red-600"
                    @tap="handleDeletePost(post.id)"
                  >
                    <text class="fa fa-trash"></text>
                  </button>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 暂无动态提示 -->
        <view v-else class="text-center py-12">
          <view class="text-6xl text-gray-300 mb-4">
            <text class="fa fa-file-text-o"></text>
          </view>
          <text class="text-xl font-semibold text-gray-500 mb-2">暂无动态</text>
          <text class="text-gray-400">快来发布你的第一条动态吧！</text>
          <button class="btn-primary mt-6" @tap="showPostModal">
            <text class="fa fa-plus mr-1"></text>发布动态
          </button>
        </view>
      </view>
    </view>

    <!-- 发布动态弹窗 (从主容器中移出) -->
    <uni-popup ref="postModal" type="center">
      <view class="bg-white rounded-xl p-6 w-full max-w-lg mx-4">
        <view class="flex justify-between items-center mb-4">
          <text class="text-lg font-bold">发布新动态</text>
          <button class="text-gray-400 hover:text-gray-600" @tap="hidePostModal">
            <text class="fa fa-times"></text>
          </button>
        </view>
        <textarea 
          v-model="newPost.content"
          class="w-full h-32 p-3 border rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-primary/20" 
          placeholder="分享你的想法..."
        ></textarea>
        <view class="flex justify-end mt-4 gap-3">
          <button class="btn-outline" @tap="hidePostModal">取消</button>
          <button 
            class="btn-primary" 
            @tap="submitPost"
            :disabled="isSubmitting"
          >
            {{ isSubmitting ? '发布中...' : '发布' }}
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getUserPosts, createPost, deletePost } from '@/api/post'
import { debounce } from '@/utils/helpers'
import { generateAvatarSvg } from '@/utils/avatar'

export default {
  data() {
    return {
      posts: [],
      isLoading: false,
      isSubmitting: false,
      newPost: {
        content: ''
      },
      isMobile: false,
      isDarkMode: false
    }
  },
  onReady() {
    // 检查登录状态
    const userId = uni.getStorageSync('userId')
    if (!userId) {
      uni.reLaunch({
        url: '/pages/login/login'
      })
      return
    }

    this.fetchUserPosts()
  },
  onLoad() {
    const systemInfo = uni.getSystemInfoSync();
    this.isMobile = systemInfo.windowWidth < 768;
    this.isDarkMode = systemInfo.theme === 'dark';
  },
  methods: {
    getAvatarUrl(config) {
        return generateAvatarSvg(config);
    },
    // 加载动态
    async fetchUserPosts() {
      if (this.isLoading) return

      try {
        this.isLoading = true
        const userId = uni.getStorageSync('userId')
        const response = await getUserPosts(userId)
        
        if (!response || !response.posts) {
          throw new Error('获取数据失败')
        }
        
        this.posts = response.posts
      } catch (error) {
        console.error('加载动态失败:', error)
        uni.showToast({
          title: error.message || '加载失败，请稍后重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.isLoading = false
      }
    },

    // 导航到动态广场
    navigateToSquare() {
      uni.navigateTo({
        url: '/pages/square/square',
        fail: (err) => {
          console.error('导航失败:', err)
          uni.showToast({
            title: '页面跳转失败，请重试',
            icon: 'none'
          })
        }
      })
    },

    // 显示发布动态弹窗
    showPostModal() {
      if (!this.$refs.postModal) return
      this.$refs.postModal.open()
    },

    // 隐藏发布动态弹窗
    hidePostModal() {
      if (!this.$refs.postModal) return
      this.$refs.postModal.close()
      this.newPost.content = ''
    },

    // 提交动态
    async submitPost() {
      if (!this.newPost.content.trim()) {
        uni.showToast({
          title: '请输入动态内容',
          icon: 'none'
        })
        return
      }

      if (this.isSubmitting) return

      try {
        this.isSubmitting = true
        await createPost({
          content: this.newPost.content.trim()
        })
        
        uni.showToast({
          title: '发布成功',
          icon: 'success'
        })
        
        this.hidePostModal()
        await this.fetchUserPosts()
      } catch (error) {
        console.error('发布失败:', error)
        uni.showToast({
          title: error.message || '发布失败，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.isSubmitting = false
      }
    },

    // 删除动态
    handleDeletePost(postId) {
      if (!postId) return

      uni.showModal({
        title: '提示',
        content: '确定要删除这条动态吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await deletePost(postId)
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              await this.fetchUserPosts()
            } catch (error) {
              console.error('删除失败:', error)
              uni.showToast({
                title: error.message || '删除失败，请重试',
                icon: 'none',
                duration: 2000
              })
            }
          }
        }
      })
    },

    // 格式化时间
    formatTime(timestamp) {
        if (!timestamp) return '未知时间';
        if (typeof timestamp === 'string') {
            timestamp = timestamp.replace(/-/g, '/').replace(' +0000 UTC', '');
        }
        const date = new Date(timestamp);
        if (isNaN(date.getTime())) return '未知时间';
        
        const now = new Date();
        const diff = now.getTime() - date.getTime();
        
        if (diff < 60000) return '刚刚';
        if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
        if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
        
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        return `${year}/${month}/${day} ${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}`;
    },

    // 返回上一页
    navigateBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style src="./my-posts.css"></style> 